<?php
session_start();

require_once "db.php";
$username = db_escape($_POST['user']);
$password = db_escape(md5($_POST['pass']));
$_SESSION['utype'] = 1;
function check_user_data($username, $pass){
	$query = "SELECT * FROM accounts WHERE username='$username' AND password='$pass'";
	$result = db_query($query);
	if ($result->num_rows == 0) {
		return false;
	}
	$row = db_get_row($result);
	return $row;
}
function print_wrong_login(){
	$response = array("response" => "1", "msg" => "Username or password don't match", "pic" => "/denied1.png");
	echo json_encode($response);
	exit();
}

function no_such_account(){
	$response = array("response" => "1", "msg" => "Account with that name doesn't exists!", "pic" => "/denied1.png");
	echo json_encode($response);
	exit();
}


if (isset($username, $password)) {
	$row = check_user_data($username, $password);
	if ($row) {
		if($row['active_or_not'] == '0'){
		$_SESSION['uid'] = $row['idaccounts'];
		$_SESSION['uusername'] = $row['username'];
		$_SESSION['umail'] = $row['mail'];
		$_SESSION['utype'] = $row['type'];
		$_SESSION['ufav1'] = $row['favgenre1'];
		$_SESSION['ufav2'] = $row['favgenre2'];
		$_SESSION['ufav3'] = $row['favgenre3'];
		$response = array("response" => "0", "msg" => "Login Successfull", "uid" => $_SESSION['uid'], 
			"uusername" => $_SESSION['uusername'], "umail" => $_SESSION['umail'], "utype" => $_SESSION['utype'], 
			"ufav1" => $_SESSION['ufav1'], "ufav2" => $_SESSION['ufav2'], "ufav3" => $_SESSION['ufav3'], "pic" => "/check.png");
		echo json_encode($response);
		exit();
		}
		else no_such_account();		
	}
	else print_wrong_login();
}

